package com.xiaomi.eco.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaomi.eco.dal.entity.EcoCompanyWebMappingEntity;
import com.xiaomi.eco.dal.entity.TbEcoApplicationCompanyEntity;
import com.xiaomi.eco.service.EcoCompanyWebMappingEntityService;
import com.xiaomi.eco.service.TbEcoApplicationCompanyEntityService;
import com.xiaomi.eco.service.impl.EcoCompanyWebMappingEntityServiceImpl;
import com.xiaomi.eco.service.impl.TbEcoApplicationCompanyEntityServiceImpl;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
public class EcoRobotMethod {

//    @Autowired
//    private  RestTemplate restTemplate;

    private static ObjectMapper objectMapper = new ObjectMapper();

    @Value("${Feishu.appId}")
    private  String appId;

    @Value("${Feishu.appSecret}")
    private  String appSecret;



    public  String getTenantAccessToken() {
        String tenantAccessToken = "";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String requestTenantAccessToken = String.format(EcoServiceQualityAlarm.requestTenantAccessToken, appId, appSecret);
        String tenantAccessTokenResponse = postForObject(EcoServiceQualityAlarm.tenantAccessTokenUrl, requestTenantAccessToken);
        JsonNode TenantAccessTokenResponJsonNode=null;
        try {
            TenantAccessTokenResponJsonNode = objectMapper.readTree(tenantAccessTokenResponse);
        } catch (JsonProcessingException e) {
            log.error("json解析失败: {}",tenantAccessTokenResponse);
        }
        tenantAccessToken = TenantAccessTokenResponJsonNode.get(EcoServiceQualityAlarm.tenantAccessToken).asText();
        return tenantAccessToken;
    }

    //@Autowired
    //TbEcoApplicationCompanyEntityService tbEcoApplicationCompanyEntityService;

//    @Autowired
//    EcoCompanyWebMappingEntityService ecoCompanyWebMappingEntityService;


    //把飞书和机器人的任务增删改查都封装下

    public static String postForObject(String requestUrl, String requestTask) {
        //请求头
        HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate=new RestTemplate();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //处理与请求
        String response = null;
        HttpEntity<String> TaskEntity = new HttpEntity<>(requestTask, headers);
        try {
            response = restTemplate.postForObject(requestUrl, TaskEntity, String.class);
        } catch (RestClientException e) {
            log.error("postRequest error={}", e.getMessage());
        }
        return response;
    }

    public static String postForObject(String tenantAccessToken,String requestUrl, String requestTask) {
        //请求头
        RestTemplate restTemplate=new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set(EcoServiceQualityAlarm.AUTHORIZATION, EcoServiceQualityAlarm.BEARER + tenantAccessToken);
        headers.setContentType(MediaType.APPLICATION_JSON);
        //处理与请求
        String response = null;
        HttpEntity<String> TaskEntity = new HttpEntity<>(requestTask, headers);
        try {
            response = restTemplate.postForObject(requestUrl, TaskEntity, String.class);
        } catch (RestClientException e) {
            log.error("postRequest error={}", e.getMessage());
        }
        System.out.println(response);
        return response;
    }



    /*
     * 获取哪个用户的OpenId
     * */
//    public static String getOpenId(String userInfo, String Type) {
//        String mobile = "";
//        String openId = "";
//        TbEcoApplicationCompanyEntityService tbEcoApplicationCompanyEntityService=new TbEcoApplicationCompanyEntityServiceImpl();
//        EcoCompanyWebMappingEntityService ecoCompanyWebMappingEntityService=new EcoCompanyWebMappingEntityServiceImpl();
//        if (Type.equals(EcoServiceQualityAlarm.principalPhone)) {
//            mobile = userInfo;
//        } else if (Type.equals(EcoServiceQualityAlarm.APPLICATION)) {
//            List<TbEcoApplicationCompanyEntity> tbEcoApplicationCompanyEntityList = tbEcoApplicationCompanyEntityService.list();
//
//            Map<String, TbEcoApplicationCompanyEntity> applicationMap = tbEcoApplicationCompanyEntityList.stream().collect(Collectors.toMap(TbEcoApplicationCompanyEntity::getApplicationId, Function.identity()));
//            TbEcoApplicationCompanyEntity applicationEntity = applicationMap.get(userInfo);
//            if (applicationEntity == null) {
//                return "";
//            }
//            List<EcoCompanyWebMappingEntity> ecoCompanyWebMappingEntityList = ecoCompanyWebMappingEntityService.list();
//            Map<String, EcoCompanyWebMappingEntity> companyWebMappingMap = ecoCompanyWebMappingEntityList.stream().collect(Collectors.toMap(EcoCompanyWebMappingEntity::getCompanyName, Function.identity()));
//            if (companyWebMappingMap == null) {
//                return "";
//            }
//            EcoCompanyWebMappingEntity companyEntity = companyWebMappingMap.get(applicationEntity.getCompanyName());
//            if (companyEntity == null) {
//                return "";
//            }
//            mobile = companyEntity.getPrinciPhone();
//        }
//        ResponseEntity<String> userIdResponse = exchangeRequest(getTenantAccessToken(), EcoServiceQualityAlarm.userIdUrl + mobile, EcoServiceQualityAlarm.BODY, HttpMethod.GET);
//        JsonNode jsonNode = null;
//        if (userIdResponse.getStatusCode().is2xxSuccessful()) {
//            String userIdBody = userIdResponse.getBody();
//            try {
//                jsonNode = objectMapper.readTree(userIdBody);
//            } catch (JsonProcessingException e) {
//                log.error("解析用户信息失败，json为: {}",jsonNode);
//            }
//            if (jsonNode.get(EcoServiceQualityAlarm.MSG).asText().equals(EcoServiceQualityAlarm.SUCCESS)) {
//                JsonNode mobileUsersNode = jsonNode.get(EcoServiceQualityAlarm.DATA).get(EcoServiceQualityAlarm.MOBILE_USERS);
//                Iterator<Map.Entry<String, JsonNode>> mobileUsersIterator = mobileUsersNode.fields();
//                while (mobileUsersIterator.hasNext()) {
//                    Map.Entry<String, JsonNode> entry = mobileUsersIterator.next();
//                    JsonNode usersArrayNode = entry.getValue();
//                    for (JsonNode userNode : usersArrayNode) {
//                        openId = userNode.get(EcoServiceQualityAlarm.OPEN_ID).asText();
//                    }
//                }
//            }
//        } else {
//            log.info("响应错误: {}" + userIdResponse.getStatusCode());
//            log.info("响应错误: {}" + userIdResponse.getBody());
//        }
//        return openId;
//    }

    public static ResponseEntity<String> exchangeRequest(String tenantAccessToken, String requestUrl, String requestTask, HttpMethod requeststatus) {
        HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate=new RestTemplate();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set(EcoServiceQualityAlarm.AUTHORIZATION, EcoServiceQualityAlarm.BEARER + tenantAccessToken);

        //连接与超时设置
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setConnectTimeout(EcoServiceQualityAlarm.CONNECTTIMEOUT);
        requestFactory.setReadTimeout(EcoServiceQualityAlarm.READTIMEOUT);
        restTemplate.setRequestFactory(requestFactory);
        HttpEntity<String> TaskEntity = new HttpEntity<>(requestTask, headers); // 使用空字符串作为请求体，或者完全省略（取决于你的RestTemplate版本）
        ResponseEntity<String> TaskResponse = null;
        try {
            TaskResponse = restTemplate.exchange(requestUrl, requeststatus, TaskEntity, String.class);
        } catch (RestClientException e) {
            log.error("exchangeRequet error={}", e.getMessage());
            log.error("请求地址为: {}", requestUrl);
        }
        return TaskResponse;
    }



    public static String selectTaskFeiShu(String tenantAccessToken,String taskId){
        //String tenantAccessToken=getTenantAccessToken();
        String searchUrlResult = String.format(EcoServiceQualityAlarm.searchTaskUrl, taskId);
        ResponseEntity<String> searchResponse=exchangeRequest(tenantAccessToken,searchUrlResult,EcoServiceQualityAlarm.BODY,HttpMethod.GET);
        if(searchResponse==null){
            log.info("selectTaskFeiShu result is null");
            return "";
        }
        String resData=searchResponse.getBody();
        log.info("selectTaskFeiShu get resData:"+resData.toString());
        return resData;
    }

    public static String insertTaskFeishu(String tenantAccessToken,String requestTask) {
        //String tenantAccessToken=getTenantAccessToken();
        String resData=postForObject(tenantAccessToken,EcoServiceQualityAlarm.insertTaskFeishuUrl,requestTask);
        if(resData==null){
            log.info("insertTaskFeishu fail");
            return null;
        }
        System.out.println("resData:        "+resData);
        return resData;
    }

    public static boolean updateTaskFeishu(String tenantAccessToken,String requestUpdateTask,String taskId){
        //String tenantAccessToken=getTenantAccessToken();
        String patchUrlResult = String.format(EcoServiceQualityAlarm.patchTaskUrl, taskId);
        ResponseEntity<String> responseEntity=exchangeRequest(tenantAccessToken,patchUrlResult,requestUpdateTask,HttpMethod.PATCH);
        if(responseEntity==null){
            log.info("updateTaskFeishu fail");
            return false;
        }
        log.info("updateTaskFeishu get resData:"+responseEntity.toString());
        String resStatusCode= String.valueOf(responseEntity.getStatusCodeValue());
        return "200".equals(resStatusCode);
    }

    public static boolean deleteTaskFeishu(String tenantAccessToken,String taskId){
        //String tenantAccessToken= getTenantAccessToken();
        String delUrlResult = String.format(EcoServiceQualityAlarm.delTaskUrl, taskId);
        ResponseEntity<String> responseEntity=exchangeRequest(tenantAccessToken,delUrlResult,EcoServiceQualityAlarm.BODY,HttpMethod.DELETE);
        if(responseEntity==null){
            log.info("deleteTaskFeishu fail");
            return false;
        }
        log.info("deleteTaskFeishu get resData:"+responseEntity.toString());
        String resStatusCode= String.valueOf(responseEntity.getStatusCodeValue());
        return "200".equals(resStatusCode);
    }
}
